package personal.lijun.skeleton.web.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/19 15:10
 */
//@Configuration
//@AutoConfigureAfter({RedisAutoConfiguration.class,RedisHttpSessionConfiguration.class})
public class RedisConfig {
    @Autowired
    public void RedisOperationsSessionRepository(RedisOperationsSessionRepository redisOperationsSessionRepository){
        RedisOperations<Object,Object> sessionRedisOperations = redisOperationsSessionRepository.getSessionRedisOperations();
        if(sessionRedisOperations instanceof RedisTemplate){
            RedisTemplate redisTemplate = (RedisTemplate)sessionRedisOperations;
            //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
            Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
            redisTemplate.setValueSerializer(serializer);
            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            serializer.setObjectMapper(mapper);

            redisTemplate.setValueSerializer(serializer);
            //使用StringRedisSerializer来序列化和反序列化redis的key值
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//            redisTemplate.setHashValueSerializer(serializer);
            redisTemplate.setValueSerializer(serializer);
        }
    }
}
